package juan.happyge.plugin.myi.service.book;

import juan.happyge.plugin.myi.config.BookConfig;
import juan.happyge.plugin.myi.config.ConfigManage;
import juan.happyge.plugin.myi.helper.MyNotifier;
import juan.happyge.plugin.myi.pojo.crawler.CrawlerChapterDetailPojo;
import juan.happyge.plugin.myi.service.book.crawler.AbstractBookCrawler;
import juan.happyge.plugin.myi.service.book.crawler.BookCrawlerBQG;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BookCrawlerBuilder {

    /**
     * 基础配置
     */
    BookConfig bookConfig = ConfigManage.getInstance().getBookConfig();

    public static AbstractBookCrawler abstractBookCrawler;

    private AbstractBookCrawler builder(String crawlerWebsite){
        switch (crawlerWebsite){
            case "笔趣阁" : return new BookCrawlerBQG();
            default: return null;
        }
    }


    /**
     * 开始连载
     */
    public void startSerial(){
        //指定爬取网站
        abstractBookCrawler = new BookCrawlerBuilder().builder(bookConfig.getCrawlerWebsite());
        //加载文件
        BookService.loadBook(bookConfig.getBookPath());
        //解析出nextUrl
        String nextUrl = getBookStartUrl();

        if(StringUtils.isNotEmpty(nextUrl)){
            //开始爬取
            doCrawler(nextUrl);
            //重新加载文件
            BookService.loadBook(bookConfig.getBookPath());
        }
    }
    
    /**
     * 执行爬取
     */
    private void doCrawler(String url) {
        Document document = abstractBookCrawler.reloadHtml(url);
        CrawlerChapterDetailPojo crawlerChapterDetailPojo = abstractBookCrawler.analyze(document);
        if(Objects.isNull(crawlerChapterDetailPojo)){
            System.out.println("爬取完成");
            return;
        }
        abstractBookCrawler.saveChapter(crawlerChapterDetailPojo);

        //判断是否爬取下一章
        if(true){
            try {
                Thread.sleep(5000);
                doCrawler(crawlerChapterDetailPojo.getNextUrl());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    Pattern urlPattern = Pattern.compile("^url=http");
    /**
     * 获取书籍开始爬取的url
     * 逻辑是从文本最后一行开始读，最高只读取3000行的内容
     * @return
     */
    private String getBookStartUrl(){
        int readLineNum = BookService.getTotalLines() > 3000 ? 3000 : BookService.getTotalLines();
        for (int i = 1; i <= readLineNum; i++) {
            String lastLine = BookService.getBookParagraph(BookService.getTotalLines() - 1,1);
            Matcher m = urlPattern.matcher(lastLine);
            if(m.find()){
                return lastLine.replace("url=","");
            }
        }
        return null;
    }



}
